import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseInterceptors,
  UploadedFile,
  Res,
} from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiOperation, ApiTags, ApiConsumes, ApiBody } from '@nestjs/swagger';
import { zip } from 'compressing';
import type { Response } from 'express';
import { join } from 'path';
@Controller('upload')
@ApiTags('upload模块')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}
  @Post('album')
  @ApiOperation({
    summary: '上传文件',
    description: '根共享动态接口',
  })
  @ApiConsumes('multipart/form-data') // 设置请求的 content-type 为 multipart/form-data
  @ApiBody({
    description: '上传单个文件',
    type: 'object',
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string', // 声明文件类型为字符串，用于 Swagger 文档生成
          format: 'binary', // 声明文件格式为 binary，用于 Swagger 文档生成
        },
      },
    },
  })
  /* 1 用于在请求到达路由处理器前执行中间件逻辑
     2 用于处理文件上传中间件，其中 'file' 是表单字段的名称，
    它告诉中间件将客户端上传的文件存储在名为 'file' 的表单字段中 */
  @UseInterceptors(FileInterceptor('file'))
  // 3这是一个参数装饰器，用于在路由处理器函数中获取已上传的文件
  upload(@UploadedFile() file) {
    console.log(file);
    return { originalname: file.originalname, filename: file.filename };
  }

  @Get('export')
  @ApiOperation({
    summary: '下载文件 url的方式',
  })
  downLoad(@Res() res: Response) {
    // E:\work\demo\project\nest-project\dist\upload
    // console.log('__dirname', __dirname);
    const url = join(__dirname, '../images/1690097433115.png');
    res.download(url);
    // return  true
  }

  @Get('stream')
  async down(@Res() res: Response) {
    const url = join(__dirname, '../images/1690097433115.png');
    const tarStream = new zip.Stream();
    await tarStream.addEntry(url);

    res.setHeader('Content-Type', 'application/octet-stream');

    res.setHeader('Content-Disposition', `attachment; filename=games`);

    tarStream.pipe(res);
  }
}
